/* IDs for elements which are used several times */
var FORM = "form";
var SELECT_CATEGORY = "categoryList";
var CHECKBOX_ALL_DAY = "allDayEvent";
var TEXT_TIME_START = "startTime";
var TEXT_TIME_END = "endTime";
var FILE_IMAGE = "image";


/** Calls the functions which prepare the form */
function initForm() {
    loadCategoryList();
}


/**
 * Fetches the different categories and
 * adds them to the selection. 
 */
function loadCategoryList() {
    var list = document.getElementById(SELECT_CATEGORY);
   
    while (list.firstChild) list.removeChild(list.firstChild);
    
   
    /* load categories from storage */
    var i;
    for (i = 0; i<storage.categories.length; i++) {
        var option = document.createElement("option");
        
        /* make select options selectable for editing */
        var attribute = document.createAttribute("id");
        attribute.value = "category" + storage.categories[i].name;
        option.setAttributeNode(attribute);
        
        option.innerHTML = storage.categories[i].name;
        list.add(option);
    }
}


/** Adds a category which can be assigned to an event */
function createCategory() {
    if (document.getElementById("newCategory").value) {
        var request = new XMLHttpRequest();
        request.open("POST", URL_START, true);
        request.onreadystatechange = function () {
            alertError(request, "create category");
            if (request.status !== 200) {
            }
        };

        var formData = new FormData();

        formData.append("user", USER);
        formData.append("action", "add-category");
        formData.append("format", "json");
        
        formData.append("name", document.getElementById("newCategory").value);
        request.send(formData);
        
        document.getElementById("newCategory").value = "";
        
        initialize();
    } else {
        alert("Field is empty.\nNo category created.");
    }
}

/**
 * Gets the selected categories in the form.
 * 
 * @returns {String[]} categories array with the seleced category ids 
 */
function getSelectedCategories() {
    var categories = [];
    var options = document.getElementById(SELECT_CATEGORY).options;
    
    for (var i=0; i<options.length; i++) {
        if (options[i].selected) {
            categories[categories.length] = storage.findCategoryId(options[i].value);
        }
    }
    return categories;
}

/**
 * Creates an event form the Data in the Form.
 */
function submitData() {
    var request = new XMLHttpRequest();
    
    var catId = getSelectedCategories();
    var file = document.getElementById("image").files[0];
    
    request.open("POST", URL_START, true);
    request.onreadystatechange = function () {
        alertError(request, "submit data");
        if (request.readyState === 4 && (request.status === 200 || request.status === 0)) {
            var eventId = JSON.parse(request.responseText).add.id;
            
            for (var i=0; i<catId.length; i++) {
                mapCategoryToEvent(eventId, catId[i]);
            }
            
            mapImageToEvent(eventId, file); // -> if image mapping is complete -> refresh calendar
            hideForm();
            
        } else if (request.status !== 200 && request.status !== 0){
            alertError(request, "submit event data");
        }
    };

    var formData = new FormData();
    
    /* add information for action on server */
    formData.append("user", USER);
    formData.append("action", "add");
    formData.append("format", "json");
    
     
    request.send(appendFormInformation(formData));
}

/**
 * Appends the information from the form to the FormData-Object.
 * 
 * @param {FormData} formData which is prepared for adding or editing
 * @returns {FormData} FormData object with information of event
 */
function appendFormInformation(formData) {
  /* add data from form */
    formData.append("title", document.getElementById("title").value);
    formData.append("location", document.getElementById("location").value);
    formData.append("organizer", document.getElementById("mail").value);
    
    var start = new Date((document.getElementById("startDate").value)+ "T" + (document.getElementById("startTime").value));
    var end = new Date((document.getElementById("endDate").value)+ "T" + (document.getElementById("endTime").value));
    
    if (start > end) {
        alert("Start date is later than end end time.\nStart date was set to end date with start time 00:00");
        start = (document.getElementById("endDate").value)+ "T00:00";
    }
    
    formData.append("start", (document.getElementById("startDate").value)+ "T" + (document.getElementById("startTime").value));
    formData.append("end", (document.getElementById("endDate").value)+ "T" + (document.getElementById("endTime").value));
    formData.append("status", (document.getElementById("statusList").value));
    
    if ((document.getElementById("allDay").checked)) {
        formData.append("allday", "1");
    } else {
        formData.append("allday", "0");
    }
    
    formData.append("webpage", (document.getElementById("webpage").value));  
    
    return formData;
}


/**
 * Maps the given Event to the given Category
 * 
 * @param {String} eventId id of the event
 * @param {String} categoryId id of the category
 */
function mapCategoryToEvent(eventId, categoryId) {
    // assign event to category
    var catRequest = new XMLHttpRequest();
    
    catRequest.open("POST", URL_START, true);
    catRequest.onreadystatechange = function () {
        alertError(catRequest, "map category to event");
        if (catRequest.readyState === 4 && (catRequest.status === 200 || catRequest.status === 0)) {
            initialize();
        } else if (catRequest.status !== 200) {
            
        }
    };

    var formData = new FormData();
    formData.append("user", USER);
    formData.append("action", "put-category");
    formData.append("format", "json");
    
    formData.append("event", eventId);
    formData.append("category", categoryId);

    catRequest.send(formData);
}


/**
 * Maps the Event with the given id to the image selected in the form.
 * 
 * @param {String} eventId id of the Event
 * @param {File} file object of the image
 */
function mapImageToEvent(eventId, file) {
    if (file) {
        var imgRequest = new XMLHttpRequest();
        imgRequest.open("POST", URL_START, true);
        imgRequest.onreadystatechange = function () {
            alertError(imgRequest, "map image to event");
            if (imgRequest.readyState === 4 && (imgRequest.status === 200 || imgRequest.status === 0)) {
                hideForm();
                initialize();
            } else if (imgRequest.status !== 200 && imgRequest.status !== 0) {
                
            }
        };

        var data = new FormData();
        data.append("user", USER);
        data.append("action", "upload-image");
        data.append("format", "json");

        data.append("id", eventId);
        data.append("file", file);
        
        imgRequest.send(data);
    }
}




/**
 * Is called if the checkbox, which indicates a all-day event, is changed. 
 * 
 * @param {checkbox} checkbox 
 */
function allDayChanged(checkbox) {
    allDayEvent(checkbox.checked);
}


/**
 * Disables the editing of the textinput for start and end time. 
 * Furthermore it sets the start time to 00:00 ad the end time to 23:59. 
 * 
 * @param {boolean} allDayEvent
 */
function allDayEvent(allDayEvent) {
    var startTime = document.getElementById(TEXT_TIME_START);
    var endTime = document.getElementById(TEXT_TIME_END);
    if (allDayEvent) {
        startTime.readOnly = true;
        startTime.value = "00:00";
        
        endTime.readOnly =  true;
        endTime.value = "23:59";
    } else {
        startTime.readOnly = false;
        startTime.value = "";
        
        endTime.readOnly = false;
        endTime.value = "";
    }
}

/** Removes the image path form the input element.  */
function removeImage() {
    document.getElementById(FILE_IMAGE).value = "";
    document.getElementById("imgURL").innerHTML = "";
}

/**
 * Called if the selected image changes. 
 * 
 * @param {type} select
 */
function imgChanged(select) {
    document.getElementById("imgURL").innerHTML = select.files[0].name;
}

/** Shows the form to create a new entry. */
function showForm() {
   document.getElementById(FORM).style.display='inline-block';
}

/** Hides the form and resets it´s content.  */
function hideForm() {
    var form = document.getElementById(FORM);
    form.style.display = 'none';
    form.reset();
    document.getElementById("imgURL").innerHTML = "";
    setFormEditMode(false);
}
